package com.solvePlat.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.auth0.jwt.JWT;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.solvePlat.dao.*;
import com.solvePlat.entity.*;
import com.solvePlat.shiro.JWTToken;
import com.solvePlat.util.JWTUtil;
import com.solvePlat.util.RedisUtil;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class WorkInfoServiceImpl implements com.solvePlat.service.WorkInfoService {
    @Resource
    private WorkInfoMapper workInfoMapper;

    @Resource
    private WorkInfoTopicMiddleMapper workInfoTopicMiddleMapper;

    @Resource
    private WorkInfoCommentMapper workInfoCommentMapper;

    @Resource
    private UserFollowMapper userFollowMapper;

    @Resource
    private TopicClassificationMapper topicClassificationMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private RedisUtil redisUtil;

    @Override
    public PageInfo selectWorkInfoByPage(WorkInfo workInfo){
        PageHelper.startPage(workInfo.getPageNum(),workInfo.getPageSize());
        List<WorkInfo> workInfoList = workInfoMapper.searchWorkInfoList(workInfo);
        PageInfo<WorkInfo> pageInfo = new PageInfo<WorkInfo>(workInfoList);
        return pageInfo;
    }



    @Override
    public String saveWorkInfoReturnUuid(WorkInfo workInfo) throws Exception{
        if (StringUtils.isEmpty(workInfo.getUuid())){
            JWTToken jwtToken = (JWTToken) SecurityUtils.getSubject().getPrincipal();
            if ("1".equals(workInfo.getType())){//如果是提的问题,需要判断悬赏积分是否足够
                User user = userMapper.selectUserAllInfo(jwtToken.getUserId());
                if (user.getIntegral().intValue() >= Integer.valueOf(workInfo.getRewardGrade()).intValue()){
                    userMapper.reduceUserIntegral(Integer.valueOf(workInfo.getRewardGrade()),jwtToken.getUserId());
                }else{
                    throw new Exception("当前积分不足!");
                }
            }
            workInfo.setStatus("0");
            workInfo.setCreaterid(jwtToken.getUserId());
            workInfo.setUuid(UUID.randomUUID().toString());
            workInfoMapper.insert(workInfo);
            batchInsertWorkInfoTopicMiddle(workInfo);
            //减去用户积分信息
        }else{
            workInfoMapper.updateByPrimaryKeySelective(workInfo);
            //首先删除原来的分类信息
            WorkInfoTopicMiddleExample workInfoTopicMiddleExample = new WorkInfoTopicMiddleExample();
            workInfoTopicMiddleExample.createCriteria().andWorkInfoIdEqualTo(workInfo.getUuid());
            workInfoTopicMiddleMapper.deleteByExample(workInfoTopicMiddleExample);
            //再添加分类信息
            batchInsertWorkInfoTopicMiddle(workInfo);
        }
        return workInfo.getUuid();
    }

    public void batchInsertWorkInfoTopicMiddle(WorkInfo workInfo){
        for (String topicClass : workInfo.getTopicClassification()){
            WorkInfoTopicMiddle workInfoTopicMiddle = new WorkInfoTopicMiddle();
            workInfoTopicMiddle.setUuid(UUID.randomUUID().toString());
            workInfoTopicMiddle.setWorkInfoId(workInfo.getUuid());
            workInfoTopicMiddle.setTopicClassificationId(topicClass);
            workInfoTopicMiddleMapper.insert(workInfoTopicMiddle);
        }
    }

    public WorkInfoExtend getWorkInfo(WorkInfo workInfo){
        WorkInfoExtend workInfoExtend = new WorkInfoExtend();
        //得到任务信息
        WorkInfo workInfoNew = workInfoMapper.selectByPrimaryKey(workInfo.getUuid());
        workInfoExtend.setWorkInfo(workInfoNew);

        //查询当前评论一共多少,

        WorkInfoCommentExample workInfoCommentExample = new WorkInfoCommentExample();
        workInfoCommentExample.createCriteria().andWorkinfoidEqualTo(workInfo.getUuid());

        int countComments = workInfoCommentMapper.countByExample(workInfoCommentExample);
        workInfoExtend.setComments(countComments);

        //判断当前是否已经关注
        JWTToken jwtToken = (JWTToken) SecurityUtils.getSubject().getPrincipal();
        UserFollowExample userFollowExample = new UserFollowExample();
        userFollowExample.createCriteria().andFollowresourcesidEqualTo(workInfo.getUuid()).andCreatorEqualTo(jwtToken.getUserId());
        int countFollowNum = userFollowMapper.countByExample(userFollowExample);
        if (countFollowNum == 0){//检查当前任务是否被关注
            workInfoExtend.setIsFollow(false);
        }else{
            workInfoExtend.setIsFollow(true);
        }

        //查询当前任务一共关注了多少人
        UserFollowExample userFollowExamples = new UserFollowExample();
        userFollowExamples.createCriteria().andFollowresourcesidEqualTo(workInfo.getUuid());
        int follows = userFollowMapper.countByExample(userFollowExamples);
        workInfoExtend.setFollowUser(follows);

        //判断当前是否已经回答了任务
        WorkInfoCommentExample workInfoCommentExampleAnswer = new WorkInfoCommentExample();
        workInfoCommentExampleAnswer.createCriteria().andWorkinfoidEqualTo(workInfo.getUuid())
                                                .andCreatoridEqualTo(jwtToken.getUserId())
                                                .andTypeEqualTo("2")
                                                 .andCreatoridEqualTo(jwtToken.getUserId())   ;
        int isAnswer = workInfoCommentMapper.countByExample(workInfoCommentExampleAnswer);
        if (isAnswer == 0){
            workInfoExtend.setIsMeAnswer(false);
        }else{
            workInfoExtend.setIsMeAnswer(true);
        }

        List<TopicClassification>  topicClassificationList = selectTopicListByWorkInfo(workInfo);
        workInfoExtend.setTopicClassificationList(topicClassificationList);
        return workInfoExtend;
    }

    public List<TopicClassification> selectTopicListByWorkInfo(WorkInfo workInfo){
        return topicClassificationMapper.selectTopicClassificationByWorkInfoId(workInfo.getUuid());
    }

    public void addBrowseNum(WorkInfo workInfo){
        workInfoMapper.addBrowseNum(workInfo);
    }

    public PageInfo selectSelfWorkInfo(WorkInfo workInfo){
        JWTToken jwtToken = (JWTToken) SecurityUtils.getSubject().getPrincipal();
        workInfo.setCreaterid(jwtToken.getUserId());
        return selectWorkInfoByPage(workInfo);
    }

    public  PageInfo getWorkInfoRankingList(WorkInfo workInfo){
        //查询出排行榜数据
        if (redisUtil.hasKey("workInforandList")){
              return JSON.parseObject(redisUtil.get("workInforandList"),new TypeReference<PageInfo<WorkInfo>>(){});
        }else{
            PageHelper.startPage(1,10);
            List<WorkInfo> workInfoList  =  workInfoMapper.searchWorkInfoListOrderByLookNum(workInfo);
            PageInfo<WorkInfo> pageInfo = new PageInfo<WorkInfo>(workInfoList);
            redisUtil.set("workInforandList",JSON.toJSONString(pageInfo));
            redisUtil.expire("workInforandList",5, TimeUnit.MINUTES);
            return pageInfo;
        }

    }
}
